<template>
  <div class="roles">
    <div class="roles_header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card shadow="hover" class="roles_con">
      <el-button type="primary" @click="dialogAddRole = true">添加角色</el-button>

      <!-- 添加角色 -->
      <el-dialog center title="添加角色" :visible.sync="dialogAddRole" :before-close="handleClose"
        @close="addcancel">
        <el-form :model="AddRoles" label-width="100px" :rules="AddRules" ref="reference">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="AddRoles.roleName" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="AddRoles.roleDesc" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddRole = false">取 消</el-button>
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 表格 -->
      <el-table :data="rolesList" style="width: 100%">
        <!-- 嵌套表格 -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row v-for="item in props.row.children" :key="item.id" class="firLevel">
              <!-- 一级权限 -->
              <el-col :span="6">
                <div class="grid-content bg-purple">
                  <el-tag closable @close="thiListDel(props.row,item.id)">{{item.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </div>
              </el-col>
              <!-- 二、三级权限 -->
              <el-col :span="18">
                <div class="grid-content">
                  <el-row v-for="items in item.children" :key="items.id" class="secList">
                    <el-col :span="12">
                      <div class="grid-content bg-purple-light">
                        <el-tag type="success" closable @close="thiListDel(props.row,items.id)">
                          {{items.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="grid-content bg-purple">
                        <el-tag closable v-for="itemss in items.children" :key="itemss.id"
                          class="thiList" type="warning" @close="thiListDel(props.row,itemss.id)">
                          {{itemss.authName}}</el-tag>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index">
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName">
        </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
            <el-button size="mini" type="warning" @click="handlejiao(scope.$index, scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑角色 -->
      <el-dialog center title="编辑角色" :visible.sync="dialogEditorRole" :before-close="handleClose"
        @close="editorCancel">
        <el-form :model="EditorRoles" label-width="100px" :rules="AddRules" ref="referenceEditor">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="EditorRoles.roleName" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="EditorRoles.roleDesc" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogEditorRole = false">取 消</el-button>
          <el-button type="primary" @click="confirmEditor">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <!-- 分配权限树 -->
    <el-dialog title="分配权限" @close="colseDistribution" center :visible.sync="dialogRoles"
      width="50%">
      <!-- 树状图 -->
      <el-tree :data="treeList" show-checkbox node-key="id" :default-expand-all="true"
        :props="treeProps" :default-checked-keys="defaultId" ref="tree">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoles = false">取 消</el-button>
        <el-button type="primary" @click="confirmGive">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RoLes',
  data() {
    return {
      rolesList: [],
      treeList: [],
      // 添加角色框的显示
      dialogAddRole: false,
      //添加角色框的表单元素
      AddRoles: {
        roleName: '',
        roleDesc: '',
      },
      // 添加框的验证规则
      AddRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
      },
      // 编辑框的显示
      dialogEditorRole: false,
      //编辑框的表单元素
      EditorRoles: {
        roleID: '',
        roleName: '',
        roleDesc: '',
      },
      // 分配角色框的显示
      dialogRoles: false,
      // 树状图默认规则
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选中的ID数组
      defaultId: [],
      //分配角色框属于的角色ID
      giveId: '',
    }
  },
  methods: {
    async getRoleslist() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      this.rolesList = res.data
    },
    // 关闭添加框
    addcancel() {
      this.$refs.reference.resetFields()
    },
    // 确认关闭添加框、修改框
    handleClose(done) {
      this.$confirm('确认关闭?填写数据将不被保存')
        .then(() => {
          done()
        })
        .catch(() => {})
    },
    // 添加框点确认
    confirmAdd() {
      this.$refs.reference.validate(async (val) => {
        if (!val) {
          this.$message.error('抱歉，填写内容不符合格式')
          return
        }
        const { data: addres } = await this.$http.post('roles', this.AddRoles)
        console.log(addres)
        if (addres.meta.status != 201) {
          this.$message.error('添加失败，请重试')
        }
        this.$message.success('添加成功')
        this.getRoleslist()
        this.dialogAddRole = false
      })
    },
    // 点击编辑按钮
    handleEdit(a, b) {
      this.dialogEditorRole = true
      this.EditorRoles.roleID = b.id
    },
    // 关闭编辑框
    editorCancel() {
      this.$refs.referenceEditor.resetFields()
    },
    // 编辑框点确认
    confirmEditor() {
      this.$refs.referenceEditor.validate(async (val) => {
        if (!val) {
          this.$message.error('抱歉，填写内容不符合格式')
          return
        }
        const { data: editorRes } = await this.$http.put(`roles/${this.EditorRoles.roleID}`, {
          roleName: this.EditorRoles.roleName,
          roleDesc: this.EditorRoles.roleDesc,
        })
        // console.log(editorRes)
        if (editorRes.meta.status != 200) {
          this.$message.error('编辑失败，请重试')
        }
        this.$message.success('编辑成功')
        this.getRoleslist()
        this.dialogEditorRole = false
      })
    },
    // 点击删除按钮
    async handleDelete(a, b) {
      const { data: deleteres } = await this.$http.delete(`roles/${b.id}`)
      // console.log(deleteres)
      if (deleteres.meta.status != 200) {
        this.$message.error('删除失败，请重试')
      }
      this.$message.success('删除成功')
      this.getRoleslist()
    },
    // 删除三级权限
    thiListDel(a, b) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${a.id}/rights/${b}`)
          // console.log(res)
          if (res.meta.status != 200) {
            return this.$message.error('取消权限失败')
          }
          this.$message.success('取消权限成功')
          a.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 点击分配权限按钮
    async handlejiao(a, b) {
      this.dialogRoles = true
      this.giveId = b.id //传递一下角色ID值，后面用
      const { data: result } = await this.$http.get('rights/tree')
      // 获取本角色的三级节点
      this.recursiveTree(b)
      this.treeList = result.data
    },
    // 采用递归，从一级节点不断找寻三级节点，最后收录ID值(三级节点不存在children)
    recursiveTree(node) {
      if (!node.children) {
        return this.defaultId.push(node.id)
      }
      node.children.forEach((item) => {
        this.recursiveTree(item)
      })
    },
    // 关闭分配权限框
    colseDistribution() {
      this.defaultId = []
    },
    // 点击确定分配权限
    async confirmGive() {
      const arr1 = this.$refs.tree.getCheckedKeys()
      const arr2 = this.$refs.tree.getHalfCheckedKeys()
      const str = [...arr1, ...arr2].join(',')
      const { data: treeChiecked } = await this.$http.post(`roles/${this.giveId}/rights`, {
        rids: str,
      })
      if (treeChiecked.meta.status != 200) {
        this.$message.error('分配失败，请重试')
      }
      this.$message.success('分配成功')
      this.getRoleslist()
      this.dialogRoles = false
    },
  },
  created() {
    this.getRoleslist()
  },
}
</script>

<style lang='less' scoped>
.roles {
  height: 100%;
}
.roles_header {
  .el-breadcrumb-item {
    font-size: 17px;
  }
}
.roles_con {
  margin-top: 30px;
  background: #fff;
  padding: 40px 20px;
  .el-table {
    margin-top: 20px;
  }
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.firLevel {
  margin-left: 20px;
  margin-top: 15px;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ccc;
  display: flex;
  align-items: center;
}
.secList {
  margin-top: 15px;
  display: flex;
  align-items: center;
}
.thiList {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>
